﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace EncryptionServer.CrcCheck.DataAccess
{
    /// <summary>
    /// 操作数据库
    /// </summary>
    class DalData
    {
        string conStr = ConfigurationManager.ConnectionStrings["fffff"].ToString();
        SqlConnection con = null;
        /// <summary>
        /// 删除最近2天以外的所有CRC码记录
        /// </summary>
        public void DelCrc()
        {
            try
            {
                string sql = "delete from tb_RepeatCheck where createtime<'" + DateTime.Now.AddDays(-1) + "'";
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有的CRC码集合
        /// </summary>
        /// <returns></returns>
        public List<int> GetCrc()
        {
            try
            {
                string sql = "select CrcMark from tb_repeatcheck";
                List<int> listCrc = new List<int>();
                DataTable dt = new DataTable();
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand(sql, con);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    con.Open();
                    adapter.Fill(dt);
                }
                if (dt.Rows.Count == 0)
                    return listCrc;
                foreach (DataRow r in dt.Rows)
                {
                    listCrc.Add(Convert.ToInt32(r[0]));
                }
                return listCrc;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 保存新CRC
        /// </summary>
        /// <param name="listCrc"></param>
        /// <returns></returns>
        public int SaveCrc(List<int> listCrc)
        {
            try
            {
                string sql = "insert into tb_repeatCheck(CrcMark,CreateTime)";
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    con.Open();
                    foreach (int crc in listCrc)
                    {
                        string sql2 = sql + " values(" + crc + ",'" + DateTime.Now + "')";
                        cmd.CommandText = sql2;
                        cmd.ExecuteNonQuery();
                    }
                }
                return 1;       //插入成功
            }
            catch
            {
                return 0;       //插入失败
            }
        }
    }
}
